import { ref, onMounted, onUnmounted, Ref } from 'vue'
import request from '@/utils/request'
import { Toast, FormInstance } from 'vant'
import { ConsultOrderItem } from '@/types/consult'
import { OrderType } from '@/enums'
import { ApiRes } from '@/types/data'
import { ImagePreview } from 'vant'
import { OrderDetail } from '@/types/order'
import { getMedicalOrderDetail } from '@/api/order'
import { CodeType } from '@/types/user'
import { sendMobileCode } from '@/api/user'

// 封装查看处方逻辑
export const useShowPrescription = () => {
  const showPrescription = async (id?: string) => {
    if (!id) return
    // 查看处方
    const res = await request.get<ApiRes<{ url: string }>>(
      `patient/consult/prescription/${id}`
    )

    ImagePreview([res.data.data.url])
  }

  return { showPrescription }
}

// 取消问诊
export const useCancelOrder = () => {
  const loading = ref(false)

  // 取消订单
  const cancelOrder = async (item: ConsultOrderItem) => {
    try {
      loading.value = true
      await request.put(`patient/order/cancel/${item.id}`)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'

      Toast.success('取消成功~')
    } catch (error) {
      Toast.fail('取消失败~')
    } finally {
      loading.value = false
    }
  }

  return { loading, cancelOrder }
}

// 删除订单
export const useDeleteOrder = (callback?: () => void) => {
  const loading = ref(false)

  // 删除文正订单
  const deleteOrder = async (id: string) => {
    try {
      loading.value = true
      await request.delete(`patient/order/${id}`)
      loading.value = false

      callback?.()

      Toast.success('删除成功~')
    } catch (error) {
      Toast.fail('删除失败~')
    } finally {
      loading.value = false
    }
  }

  return { loading, deleteOrder }
}

// 获取药品订单详情（用在药品订单支付和药品订单详情查看）
export const useMedicalOrderDetail = (id: string) => {
  const loading = ref(false)
  const order = ref<OrderDetail>()
  onMounted(async () => {
    loading.value = true
    try {
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
      loading.value = false
    } catch (error) {
      loading.value = false
    }
  })

  return { loading, order }
}

// 发送短信验证码逻辑
export const useSendMobileCode = (mobile: Ref<string>, type: CodeType) => {
  const form = ref<FormInstance>()
  const time = ref(0)
  let timer = -1
  const send = async () => {
    if (time.value > 0) return

    try {
      await form.value?.validate('mobile')
      await sendMobileCode(mobile.value, type)
      Toast.success('发送成功~')
      time.value = 60
      // 倒计时
      clearInterval(timer)
      timer = window.setInterval(() => {
        time.value--
        if (time.value <= 0) window.clearInterval(timer)
      }, 1000)
    } catch (error) {
      console.log('validate error ', error)
    }
  }

  onUnmounted(() => {
    clearInterval(timer)
  })

  return {
    time,
    send,
    form
  }
}
